package com.bkhech.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import com.bkhech.api.feign.FileFein;
import com.bkhech.enums.SexEnum;
import com.bkhech.grace.result.GraceJSONResult;
import com.bkhech.mapper.UsersMapper;
import com.bkhech.pojo.Users;
import com.bkhech.utils.LocalDateUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * UsersService
 * 用户表 服务实现类
 *
 * @author guowm
 * @date 2024-11-01
 */
@Service
public class UsersService {

    @Resource
    private UsersMapper usersMapper;

    @Resource
    private FileFein fileFein;


    public Users createUsers(String mobile, String nickname) {
        Users users = this.initUser(mobile, nickname);
        String qrCodeUrl = getQrCodeUrl(users.getWechatNum(), "temp");
        users.setWechatNumImg(qrCodeUrl);
        usersMapper.insert(users);
        return users;
    }

    /**
     * 初始化用户信息
     * @param mobile
     * @param nickname
     * @return
     */
    private Users initUser(String mobile, String nickname) {
        Users user = new Users();
        user.setCreatedTime(LocalDateTimeUtil.now());
        user.setUpdatedTime(LocalDateTimeUtil.now());
        user.setMobile(mobile);

        String uuid = UUID.randomUUID().toString();
        String[] uuidArr = uuid.split("-");
        String wxNum = "wx" + uuidArr[0] + uuidArr[1];
        user.setWechatNum(wxNum);

        if (StrUtil.isBlank(nickname)) {
            nickname = "用户" + DesensitizedUtil.mobilePhone(mobile);
        }
        user.setNickname(nickname);
        user.setSex(SexEnum.SECRET.type);
        user.setFace("http://hbimg.huaban.com/97d26267fd3d5b921f5b07f4a4820220f2d6140d8ee4f-GQnbyY");
        user.setFriendCircleBg(StrUtil.EMPTY);
        user.setEmail(StrUtil.EMPTY);
        user.setBirthday(LocalDateTimeUtil.parseDate("1980-01-01", LocalDateUtils.DATE_PATTERN));
        user.setCountry("中国");
        user.setProvince(StrUtil.EMPTY);
        user.setCity(StrUtil.EMPTY);
        user.setDistrict(StrUtil.EMPTY);
        user.setWechatNumImg(StrUtil.EMPTY);
        String realName = "用户" + mobile;
        user.setRealName(realName);
        return user;
    }

    public Users queryMobileIfExist(String mobile) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.lambda().eq(Users::getMobile, mobile);
        return usersMapper.selectOne(usersQueryWrapper);
    }

    private String getQrCodeUrl(String wechatNum, String userId) {
        GraceJSONResult<String> result = fileFein.generatorQrCode(wechatNum, userId);
        String qrCodeUrl = result.getData();
        return qrCodeUrl;
    }
}
